﻿using LD.Host;
using LD.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;

namespace LD.Tool
{
    [Tool(Text = "扫码枪", FrmParam = "ToolScanerFrm", ToolType = ToolEnum.通讯)]
    public class ToolScaner : BaseTool
    {
        public override OpResult Execute(TB_Tool model)
        {
            try
            {
                isSuccess = false;
                stopwatch.Start();
                if (model.Param != null)
                {
                    var param = Newtonsoft.Json.JsonConvert.DeserializeObject<ScanerParam>(model.Param);
                    bool scanerSuccess = true;
                    List<Task> tasks = new List<Task>();
                    foreach (var item in param.Scaners)
                    {
                        tasks.Add(TaskScan(item));
                    }
                    Task.WaitAll(tasks.ToArray());
                    foreach (Task<OpResult> item in tasks)
                    {
                        if (!item.Result.IsSuccess)
                            scanerSuccess = false;
                    }
                    //EchoPLC(model.EchoModel);

                    isSuccess = scanerSuccess;

                    if (!isSuccess)
                        EchoPLC(model.EchoPLC);

                }
            }
            catch (Exception ex)
            {
                Log(model, ex.Message, LogLevel.严重);
            }
            finally
            {
                stopwatch.Stop();
            }
            return new OpResult() { IsSuccess = isSuccess, Message = message, ExecuteTime = stopwatch.ElapsedMilliseconds };

        }
        private Task<OpResult> TaskScan(ScanerModel model)
        {
            ScanerModel _model = model;
            return Task.Run(() =>
            {
                bool isSuccess = false;
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                string msg = string.Empty;
                try
                {
                    if (_model != null)
                    {
                        //因多线程
                        //此处警告信息不再使用ResultMsg
                        msg = $"【{_model.Name}】请求扫描";
                        Log4.Info(msg);

                        //clear barcode
                        if (_model != null)
                        {
                            Cache.SetVar(model.Value, "");
                        }

                        string barcode = Read(model);

                        if (barcode != string.Empty)
                        {
                            isSuccess = true;
                            Cache.SetVar(model.Value, barcode);
                        }
                        else
                        {
                            msg = $"【{_model.Name}】扫描失败";
                            Log4.Warr(msg);
                        }

                        PubSub.Hub.Default.Publish(new BarcodeHandle()
                        { Slot = model.Alias, Barcode = barcode });
                    }
                }
                catch (Exception ex)
                {
                    Log4.Error(ex);
                }
                finally
                {
                    stopwatch.Stop();
                }
                return new OpResult(isSuccess, msg, stopwatch.ElapsedMilliseconds);
            });
        }
        public string Read(ScanerModel scaner)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            string barcode = string.Empty;
            try
            {
                while (stopwatch.ElapsedMilliseconds < scaner.TimeOut && string.IsNullOrEmpty(barcode))
                {
                    if (CommunicateFactory.Instance.TcpIp[scaner.Name].Status == Status.成功)
                    {
                        barcode = CommunicateFactory.Instance.TcpIp[scaner.Name].Send("Start".ToLower(), 1000);
                        Log4.Info($"【{scaner.Name}】条码信息【{barcode}】");
                        if (barcode.Contains("NoRead"))
                            barcode = string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                Log4.Error($"【{scaner.Name}】{ex.Message}");
            }
            finally
            {
                stopwatch.Stop();
            }
            return barcode;
        }
    }
}
